package com.adingxiong.quickstart.project.controller;


import com.adingxiong.quickstart.common.bean.MailBean;
import com.adingxiong.quickstart.project.entity.User;
import com.adingxiong.quickstart.project.entity.vo.UserVo;
import com.adingxiong.quickstart.project.service.IRoleService;
import com.adingxiong.quickstart.project.service.IUserService;
import com.adingxiong.quickstart.result.Result;
import com.adingxiong.quickstart.result.RetCode;
import com.adingxiong.quickstart.util.MD5Utils;
import com.adingxiong.quickstart.util.MailUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiongc
 * @since 2020-05-21
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
@Api(tags = "账户接口")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private MailUtils mailUtils;


    @ApiOperation("根据条件查询用户列表")
    @GetMapping("/users")
    public Result<Page<UserVo>> getUserList(
            @ApiParam(value = "关键字") @RequestParam(value = "keywords" ,required = false) String keywords,
            @ApiParam(value = "姓名" ) @RequestParam(value = "username",required = false) String username,
            @ApiParam(value = "电话") @RequestParam(value = "phone",required = false) String phone,
            @ApiParam(value = "当前页码") @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @ApiParam(value = "每页数量") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ){
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(username)){
            wrapper.eq("username" ,username);
        }
        if(!StringUtils.isEmpty(phone)){
            wrapper.eq("tel" , phone);
        }

        if(!StringUtils.isEmpty(keywords)){
            wrapper.like("nickname",keywords).or().like("username",keywords).or().like("tel",keywords);
        }
        wrapper.orderByAsc("id");
        Page<User> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(currentPage);

        Page<UserVo> result = new Page<>();

        IPage<User> list = userService.page(page,wrapper);
        List<UserVo> res = new ArrayList<>();

        if(list != null && list.getRecords().size()>0){
            //获取所有的roleId
            List<User> arr = list.getRecords();
            List<Integer> roleIds = arr.stream().map(User::getRoleId).collect(Collectors.toList());

            boolean status = false;
            HashMap<Integer,String> names = roleService.getNameByIds(roleIds);
            for(User user : arr){
                Integer isFlag = user.getIsflag();
                if(isFlag == 1){
                    status = true;
                }else{
                    status = false;
                }
                UserVo userVo = new UserVo(user);
                userVo.setStatus(status);
                userVo.setRoleName(names.get(user.getRoleId()));
                res.add(userVo);
            }
            result.setRecords(res);
            result.setTotal(arr.size());
        }
        return new Result(RetCode.SUCCESS.getCode(),RetCode.SUCCESS.getMsg(),result);
    }

    @ApiOperation(value = "新增用户或者修改用户")
    @PostMapping("/users")
    public Result addUser(@RequestBody  User user){
        if(user == null){
            return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),false);
        }
        String pwd = user.getPassword();
        String mdPwd = MD5Utils.string2MD5(pwd);
        user.setPassword(mdPwd);
        boolean insert = userService.saveOrUpdate(user);
        if(insert){
            return new Result(RetCode.SUCCESS.getCode(),RetCode.SUCCESS.getMsg(),true);
        }else{
            return new Result(RetCode.FAIL.getCode(),RetCode.FAIL.getMsg(),false);
        }

    }

    @ApiOperation(value = "表单唯一性检验")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type" , value = "检验的类型(username,tel)" , dataType ="String" ,paramType = "query" ),
            @ApiImplicitParam(name = "value" , value = "检验的值" , dataType ="String" ,paramType = "query" )
    })
    @RequestMapping(value = "/checkOnly" ,method =  RequestMethod.GET)
    public Result onlyCheck (String type , String value){
        if(StringUtils.isEmpty(type) || StringUtils.isEmpty(value)){
            return  new Result().setCode(RetCode.PARAM_ERROR.getCode()).setMsg("参数为空");
        }
        if(!type.equals("username") && !type.equals("tel") ){
            return  new Result().setCode(RetCode.PARAM_VALUE_ERROR.getCode()).setMsg(RetCode.PARAM_VALUE_ERROR.getMsg()).setData(false);
        }
        String tip = null;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        switch (type) {
            case "username":
                queryWrapper.eq("username", value);
                tip = "用户名已存在";
                break;
            case "tel":
                queryWrapper.eq("tel", value);
                tip = "手机号码已存在";
                break;
            default:
        }
        User user = userService.getOne(queryWrapper,false);
        if(user ==null) {
            return new Result <>().setCode(RetCode.SUCCESS).setData(true).setMsg("校验通过");
        }
        return new Result <>().setCode(RetCode.SUCCESS).setData(false).setMsg(tip);
    }

    @ApiOperation(value = "根据id删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id" ,value = "用户id" ,paramType ="query")
    })
    @RequestMapping(value = "/delByid", method = RequestMethod.GET)
    public  Result delUserById (Long id ){
        if(StringUtils.isEmpty(id)){
            return  new Result<>().setCode(RetCode.NOT_FOUND).setMsg("参数为空");
        }
        User user = userService.getUserById(id);
        if(user == null){
            return  new Result<>().setCode(RetCode.FAIL.getCode()).setMsg("用户不存在");
        }
        boolean del = userService.removeById(id);
        if(del){
            return  new Result<>().setCode(RetCode.SUCCESS).setMsg("删除成功");
        }
        return  new Result<>().setCode(RetCode.FAIL).setMsg("系统异常，请稍后重试");
    }

    @PostMapping("/update")
    @ApiOperation(value = "根据指定条件修改用户信息，id是必须要的")
    public Result updateUser(User user){
        if(user == null){
            return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),false);
        }
        boolean update = userService.updateById(user);
        if(update){
            return  new Result<>().setCode(RetCode.SUCCESS).setMsg("修改成功").setData(true);
        }else{
            return  new Result<>().setCode(RetCode.SYSTEM_ERROR).setMsg(RetCode.SYSTEM_ERROR.getMsg()).setData(false);
        }
    }


    @ApiOperation(value = "用户登录(暂时不添加验证码)")
    @PostMapping(value = "/login",produces = MediaType.APPLICATION_JSON_VALUE)
    public Result Login(@RequestBody  Map<String,String> map ){
        if(CollectionUtils.isEmpty(map)){
            return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),false);
        }
        String pwd = MD5Utils.string2MD5(map.get("password"));

        User user = userService.login(map.get("username"),pwd);

        Map<String,Object> res = new HashMap<>();
        if(user !=null){
            res.put("userId",user.getId());
            res.put("username",user.getUsername());
            return new Result(RetCode.SUCCESS.getCode(),"登录成功",res);
        }
        return new Result(RetCode.FAIL.getCode(),"用户名或者密码错误",res);

    }

    @PostMapping("/resetPassword")
    @ApiOperation(value = "密码重置功能")
    public Result resetPwd(
            @ApiParam(value = "原密码",required = true) @RequestParam(value = "oldpwd" ,required = true) String oldpwd,
            @ApiParam(value = "新密码",required = true) @RequestParam(value = "newpwd" ,required = true) String newpwd,
            @ApiParam(value = "账号",required = true) @RequestParam(value = "username" ,required = true) String username
    ){
        if(StringUtils.isEmpty(oldpwd) || StringUtils.isEmpty(newpwd) || StringUtils.isEmpty(username)){
            return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),false);
        }
        if(oldpwd.equals(newpwd)){
            return new Result(RetCode.PARAM_ERROR.getCode(),"新密码与原密码一直",false);
        }
        User user = userService.login(username,MD5Utils.string2MD5(oldpwd));
        if(user == null){
            return new Result(RetCode.PARAM_VALUE_ERROR.getCode(),"密码错误",false);
        }

        user.setPassword(MD5Utils.string2MD5(newpwd));

        String email = user.getEmail();

        if(!StringUtils.isEmpty(email)){
            MailBean mailBean = new MailBean();
            mailBean.setRecipient(email);
            mailBean.setSubject("密码重置");
            String msgcode = String.valueOf(new Random().nextInt(899999) + 100000);

            String content = "<h2>尊敬的" + user.getUsername() + "：</h2>" +
                    "<p style='padding-left:50px;'>【注册验证码】: 尊敬的用户，账号为"+ username
                    +"的账户,进行密码重置操作,新密码为:<span style='font-size:16px;font-weight:bold'>" + msgcode + "</span>" +
                    " （请勿告诉他人）</p>";
            mailBean.setContent(content);
            try {
                mailUtils.sendHTMLMail(mailBean);
            } catch (Exception e) {
                return new Result().setCode(RetCode.FAIL).setMsg("邮件发送失败,邮箱有误").setData(e.toString());
            }
        }

        boolean update = userService.updateById(user);
        if(update){
            return new Result(RetCode.SUCCESS.getCode(),"重置成功,密码已发送至邮箱请注意查收(若没有填写邮箱信息,请先完善信息)",newpwd);
        }
        return  new Result<>().setCode(RetCode.FAIL).setMsg("系统异常，请稍后重试");

    }


}

